<?php

/**
 * 菜单管理
 * @author renpper
 * @date 2014-12-30
 */

namespace Admin\Controller;
class MenuController extends BaseController {
	
	private $menu_model,$levels,$targets;
	
    public function _initialize(){
		$this->menu_model = getInstance('Admin\Model\MenuModel');
    	$this->levels = array(0=>'链接', 1=>'按钮');
		$this->targets = array('navTab'=>'navTab', 'dialog'=>'dialog', '_blank'=>'_blank', '_self'=>'_self');
    }
    
    
    /**
	 * 列表页
	 */
	public function index(){
		$page = $this->view->page(count($this->menu_model->where('form')->select()));
		$menus = $this->menu_model->where('form')->order($page['orderFieldStr'])->limit("{$page['limit']},{$page['numPerPage']}")->select();
		if(is_array($menus)){
			foreach($menus as &$menu){
				$menu['level'] = $this->levels[$menu['level']];
			}
		}
		$this->assign('menus', $menus);
		$this->assign('page', $page);
		$this->display('Admin/View/Menu/index.php');
	}
	
	
	/**
	 * 查找页
	 */
	public function lookup(){
		$sql[] = 'level=0';
		$page = $this->view->page(count($this->menu_model->where('form')->select()));
		$menus = $this->menu_model->field('id,name,url')->where('form')->order($page['orderFieldStr'])->limit("{$page['limit']},{$page['numPerPage']}")->select();
		if(is_array($menus)){
			array_unshift($menus, array('id'=>0, 'name'=>'主菜单','url'=>''));
		}
		$this->assign('menus', $menus);
		$this->assign('page', $page);
		$this->display('Admin/View/Menu/lookup.php');
	}
	
	/**
	 * 添加菜单
	 */
	public function add(){
		if(count($_POST) > 0){
			$datas = $this->getFormParams();
			$datas['create_time'] = date('Y-m-d H:i:s');
			if($this->menu_model->add($datas)){
				$this->ajaxReturn(200, '添加成功', '', 'closeCurrent');
			}else{
				$this->ajaxReturn(300, '添加失败');
			}
		}else{
			$this->assign('targets', $this->targets);
			$this->assign('levels', $this->levels);
			$this->display('Admin/View/Menu/add.php');
		}
	}
	
	/**
	 * 修改菜单
	 */
	public function update(){
		if(count($_POST) > 0){
			$datas = $this->getFormParams();
			$id = $datas['id'];
			unset($datas['id']);
			if($this->menu_model->where('id='.$id)->update($datas)){
				$this->ajaxReturn(200, '修改成功', '', 'closeCurrent');
			}else{
				$this->ajaxReturn(300, '修改失败');
			}
		}else{
			$id = (int)$_REQUEST['id'];
			$this->assign('targets', $this->targets);
			$this->assign('levels', $this->levels);
			$menu_info = $this->menu_model->where("id=$id")->find();
			$parent_info = $this->menu_model->field('name')->where("id={$menu_info['parent']}")->find();
			$menu_info['parent_name'] = $parent_info['name'];
			$this->assign('menu_info', $menu_info);
			$this->display('Admin/View/Menu/update.php');
		}
	}
	
	/**
	 * 删除菜单
	 */
	public function delete(){
		$ids = $_REQUEST['ids'];
		if(!empty($ids) && $this->menu_model->where("id IN($ids)")->delete()){
			$this->ajaxReturn(200, '删除成功');
		}else{
			$this->ajaxReturn(300, '删除失败');
		}
	}
    
    
}
?>